/*
 * 财政部查看列表js
 * 依赖组件['jquery', 'bootstrapTable', 'bootstrapTableZh']
 */
(function() {
	
	require(['jquery', 'box', 'dynamicTable', 'bootstrapTable', 'bootstrapTableZh', 'select2', 'datetimepickerZh', 'form'], function(jquery, box, dynamicTable) {
		
		if(typeof jQuery === 'undefined') {	//检测jquery依赖项
			throw new Error('jquery依赖项未能加载');
		}
		
		if(typeof $.fn.bootstrapTable === 'undefined') {	//检测bootstrapTable依赖项
			throw new Error('bootstrapTable依赖项未能加载');
		}
		/*日期控件*/
		$('.form_date').datetimepicker({
			format: "yyyy-mm-dd",
	        autoclose: true,
	        pickerPosition: "bottom-left",
        	weekStart: true,
    		todayHighlight: true,
    		startView: 2,
    		minView: 2,
    		forceParse: 0
	    });
		
		/*加载是否为树下拉列表*/
		var formDataYear = [],
			formDataLevel = [{id:"0", text:"优"}, {id:"1", text:"良"},{id:"2", text:"中"}, {id:"3", text:"差"}],
			formDataTimes = [{id:"1", text:"第一次"},{id:"2", text:"第二次"},{id:"3", text:"第三次"},{id:"4", text:"第四次"},{id:"5", text:"第五次"}];
		
		//年度添加
		var date = new Date(), nowDate = date.getFullYear(), item = {}, len = nowDate-2017;
		if(nowDate >= "2017"){
			for(var i = 0; i<=len; i++){
				item = {
					id: 2017 + i,
					text: 2017 + i +"年"
				}
				formDataYear.push(item);
			}
		}
		
		$("#audit_year").select2({
			 placeholder: "年度",
			 allowClear: true,
			 data: formDataYear,
			 minimumResultsForSearch: Infinity
		 }).val("test_select2_null").trigger("change");
		
		var $eventSelect1 = null;
		$.ajax({
			url: 'report/distinctProvincialGovernment.service',
			type: 'get',
			success: function(data) {
				var _data = data.data;
				var select2Data = $.map(_data, function (obj) {
					  obj.text = obj.text || obj.provincialGovernment; 
					  obj.id = obj.provincialGovernment;
					  return obj;
					});
				$eventSelect1 = $("#audit_department").select2({
					 placeholder: "省级主管部门",
					 allowClear: true,
					 tags: true,
					 data: select2Data
					 //minimumResultsForSearch: Infinity
				 }).val("test_select2_null").trigger("change");
			}
		});
		
		$("#audit_times").select2({
			 placeholder: "第几次申报",
			 allowClear: true,
			 data: formDataTimes,
			 minimumResultsForSearch: Infinity
		 }).val("test_select2_null").trigger("change");
		
		$("#audit_level").select2({
			 placeholder: "评定等级",
			 allowClear: true,
			 data: formDataLevel,
			 minimumResultsForSearch: Infinity
		 }).val("test_select2_null").trigger("change");
		
		var $table = $('#audit_list'),	//jquery包装table对象，使其能够调用扩展后jquery的方法
	    	selections = [];
		
		function initTable() {	//加载内容
	        $table.bootstrapTable({
				width: '90%',
				columns: [
 	      			{width: '10%', field: 'year', title: '年度', align: 'center'},
	      			{width: '25%', field: 'provincialGovernment', title: '省级主管部门', align: 'center'},
	      			{width: '20%', field: 'commitTime', title: '申报时间', align: 'center'},
	      			{width: '15%', field: 'timesOfReport', title: '第几次申报', align: 'center'},
	      			{width: '15%', field: 'auditResult', title: '评定等级', align: 'center'},
	      			{width: '12%', field: 'crud', title: '操作', align: 'center', events: auditListEvent, formatter: operateFormatter}]
	        });
	        
	        setTimeout(function () {
	            $table.bootstrapTable('resetView');
	        }, 200);
	        
	        $table.on('expand-row.bs.table', function (e, index, row, $detail) {
	            if (index % 2 == 1) {
	                $detail.html('Loading from ajax request...');
	                $.get('LICENSE', function (res) {
	                    $detail.html(res.replace(/\n/g, '<br>'));
	                });
	            }
	        });
	        
	        $table.on('all.bs.table', function (e, name, args) {
	            console.log(name, args);
	        });
	        
	    }
		
	    function getIdSelections() {
	        return $.map($table.bootstrapTable('getSelections'), function (row) {
	            return row.id;
	        });
	    }
	    
	    function responseHandler(res) {
	        $.each(res.rows, function (i, row) {
	            row.state = $.inArray(row.id, selections) !== -1;
	        });
	        return res;
	    }
	    
	    function detailFormatter(index, row) {
	        var html = [];
	        $.each(row, function (key, value) {
	            html.push('<p><b>' + key + ':</b> ' + value + '</p>');
	        });
	        return html.join('');
	    }
	    
	    function operateFormatter(value, row, index) {
    		return ['<a class="open" href="javascript:void(0)" title="打开申报表">',
		            '<i class="glyphicon glyphicon-menu-hamburger"></i>',
		            '</a>',
    		        '<a class="check" href="javascript:void(0)" title="查看审核表">',
		            '<i class="glyphicon glyphicon-eye-open"></i>',
		            '</a>'].join('');
	    }
	    
	    window.auditListEvent = {
	        'click .check': function (e, value, row, index) {
	        	$('#contentNav').data('auditState', {'reportId': row.id, type: "check", auditArr: (row.auditList? row.auditList: [])});
	        	var editdata = row;
	        	var modalObj = box.auditModal('subContent'),
	    			modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
	        	var updateUrl = "system/getPage.service?path=manage/department/auditReport",
	        		_target = modalBodyId, _selector= "#subTable";
	        	orange.loadPage({url: updateUrl, target: _target, selector: _selector, success: function(response){
	        		var modal = $('#' + modalId);
	    			modal.modal({backdrop: "static"});
	    				
	    		}});
	        },
	        'click .edit': function (e, value, row, index) {
	        	$('#contentNav').data('auditState', {'reportId': row.id, type: "edit", auditArr: row.auditList? row.auditList: []});
	        	var modalObj = box.auditModal('subContent'),
	    			modalId = modalObj.modalId, modalBodyId = modalObj.modalBodyId;
	        	var updateUrl = "system/getPage.service?path=manage/department/auditReport",
	        		_target = modalBodyId, _selector= "#subTable";
	        	orange.loadPage({url: updateUrl, target: _target, selector: _selector, success: function(response){
	        		var modal = $('#' + modalId);
	    			modal.modal({backdrop: "static"});
	    			ajaxRequest();
	    		}});
	        }
	    };
	    
	    function ajaxRequest() {
	    	$.ajax({
				url:"report/retrieveReportForOtherDepartment.service",
				type:"post",
				success: function(data) {
					$table.bootstrapTable('load', data.data);
					$('#audit_list').data('$table', $table);
				},
				complete: function() {
				}
			});
	    }
	    
	    $('#button_group').find('button').bind('click', function(evt) {
	    	var target = evt.target;
	    		if(target.tagName != 'BUTTON'){
	    			return;
	    		}
	    	var year = $.trim($('#audit_year').val()), 
				provincialGovernment = $("#audit_department").val(),
				timesOfReport =$('#audit_times').val(),
				auditResult = $("#audit_level").val(),
				startTime = $("#audit_start").val(),
				endTime = $("#audit_end").val(),
				projectStatus = "",
				isNowStatus = "";
	    	
	    	var paramData = {};
	    	
	    	if(target.textContent == '查询'){
	    		paramData = {
	    	    		year:year,
	        			timesOfReport:timesOfReport,
	        			provincialGovernment:provincialGovernment,
	        			auditResult:auditResult,
	        			startDate:startTime,
	        			endDate:endTime
	    	    	};
	    	}
	    	
			$.ajax({
				url: 'report/retrieveReportForOtherDepartment.service',
				type: 'post',
				data:paramData,
				success: function(data) {
					$table.bootstrapTable('load', data.data);
				}
			});
	    });
	    
	   	initTable();//初始化table
	   	ajaxRequest();//获取全部数据
	});
	
})();
